package demo.module_login.p;


import android.text.TextUtils;

import org.json.JSONException;
import org.json.JSONObject;

import demo.module_login.R;
import demo.module_login.contract.ILoginContract;
import demo.module_login.m.LoginModule;
import demo.module_login.m.data.UserInfo;
import library.base.mvp.IContract;
import library.base.mvp.module.BaseModule;
import library.base.mvp.presenter.BasePresenter;
import library.net.retrofit.exception.RxException;
import module.common.share.SharedManager;
import module.common.util.StringUtils;

/**
 * @author Created by qiang.hou on 2018/11/30.
 * @version 1.0
 */
public class LoginPresenter extends BasePresenter implements ILoginContract.IPresenter {
    public static final String ACTION_PARAM_ERROR = "action_login_param_error";
    public static final String ACTION_LOGIN_ERROR = "action_LOGIN_ERROR";
    public static final String ACTION_LOGIN_SUCCESS = "action_LOGIN_SUCCESS";
    public static final String ACTION_CHECK_PHONE_REGISTER_ERROR = "action_check_if_phone_registered_error";
    public static final String ACTION_CHECK_PHONE_REGISTER_RESULT = "action_check_if_phone_registered_result";
    public static final String ACTION_GET_SMS_CODE_RESULT = "action_get_sms_code_RESULT";
    public static final String ACTION_USER_INFO_VERIFY_ERROR = "action_user_info_verify_error";
    private LoginModule loginModule;

    public LoginPresenter() {
        loginModule = new LoginModule();
    }

    @Override
    public void login(String phone, String x, boolean isPasswordLogin) {
        if (TextUtils.isEmpty(phone)) {
            postEvent(isPasswordLogin ? R.string.text_toast_null_user_name : R.string.text_toast_null_user_phone, ACTION_PARAM_ERROR);
            return;
        }
        if (TextUtils.isEmpty(x)) {
            postEvent(isPasswordLogin ? R.string.text_toast_null_user_password : R.string.text_toast_null_code, ACTION_PARAM_ERROR);
            return;
        }
        SharedManager.getInstance().setValue(SharedManager.KEY_LOGIN_NAME, phone);
        if (isPasswordLogin) {
            loginModule.loginByPassword(phone, x, new BaseModule.IModelObserver<UserInfo, RxException>() {
                @Override
                public void onNotify(UserInfo data) {
                    if (null == data) {
                        postEvent(R.string.text_toast_login_failed, ACTION_LOGIN_ERROR);
                    } else {
                        boolean loginOk = verifyUserInfo(data.auto, data.userEnterpriseStatus, data.userStatus, data.right, data.rightMenu);
                        if (loginOk) {
                            saveUserInfo(data);
                            postEvent(R.string.text_toast_login_success, ACTION_LOGIN_SUCCESS);
                        }
                    }
                }

                @Override
                public void onError(RxException e) {
                    // post event
                    postEvent(-1, e.getMessage(), ACTION_LOGIN_ERROR);
                }
            });
        } else {
            loginModule.loginByCode(phone, x, new BaseModule.IModelObserver<UserInfo, RxException>() {
                @Override
                public void onNotify(UserInfo data) {
                    // post event
                    if (null == data) {
                        postEvent(R.string.text_toast_login_failed, ACTION_LOGIN_ERROR);
                    } else {
                        boolean loginOk = verifyUserInfo(data.auto, data.userEnterpriseStatus, data.userStatus, data.right, data.rightMenu);
                        if (loginOk) {
                            saveUserInfo(data);
                            postEvent(R.string.text_toast_login_success, ACTION_LOGIN_SUCCESS);
                        }
                    }
                }

                @Override
                public void onError(RxException e) {
                    // post event
                    postEvent(-1, e.getMessage(), ACTION_LOGIN_ERROR);
                }
            });
        }
    }

    @Override
    public void sendSMSCode(final String phoneNumber) {
        if (!StringUtils.checkMobile(phoneNumber)) {
            postEvent(R.string.text_toast_phone_input_error, ACTION_PARAM_ERROR);
            return;
        }
        loginModule.checkRegister(phoneNumber, new IContract.IModule.IModelObserver<JSONObject, RxException>() {
            @Override
            public void onNotify(JSONObject data) {
                if (null != data) {
                    try {
                        String result = data.getString("isRegister");
                        if (null != result) {
                            if (result.equals("0")) {
                                doGetSmsCode(phoneNumber);
                            } else {
                                postEvent(false, ACTION_CHECK_PHONE_REGISTER_RESULT);
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        postEvent(R.string.text_toast_phone_is_not_registered_response_error, ACTION_CHECK_PHONE_REGISTER_ERROR);
                    }
                }
            }

            @Override
            public void onError(RxException e) {
                // post event
                postEvent(-1, e.getMessage(), ACTION_CHECK_PHONE_REGISTER_ERROR);
            }
        });
    }

    /**
     * save user info
     *
     * @param userInfo UserInfo
     */
    private void saveUserInfo(UserInfo userInfo) {
        SharedManager.getInstance().setValue(SharedManager.KEY_TOKEN_VALUE, userInfo.access_token);
        SharedManager.getInstance().setValue(SharedManager.KEY_TOKEN_TYPE, userInfo.token_type);
        SharedManager.getInstance().setValue(SharedManager.KEY_REFRESH_TOKEN_VALUE, userInfo.refresh_token);
        SharedManager.getInstance().setValue(SharedManager.KEY_TOKEN_EXPIRES_TIME,
                System.currentTimeMillis() + userInfo.expires_in * 1000 - 60000 * 60);
        SharedManager.getInstance().setValue(SharedManager.KEY_USER_STATUS, userInfo.userStatus);
        SharedManager.getInstance().setValue(SharedManager.KEY_USER_SCOPE, userInfo.scope);
        SharedManager.getInstance().setValue(SharedManager.KEY_USER_SUB, userInfo.sub);
        SharedManager.getInstance().setValue(SharedManager.KEY_USER_ENTERPRISE_STATUS, userInfo.userEnterpriseStatus);
        SharedManager.getInstance().setValue(SharedManager.KEY_USER_AUTO, userInfo.auto);
        SharedManager.getInstance().setValue(SharedManager.KEY_USER_FULL_NAME, userInfo.userFullName);
        SharedManager.getInstance().setValue(SharedManager.KEY_USER_ENTERPRISE_ID, userInfo.enterpriseId);
        SharedManager.getInstance().setValue(SharedManager.KEY_USER_ENTERPRISE_NAME, userInfo.enterpriseName);

        SharedManager.getInstance().setValue(SharedManager.KEY_USER_RIGHT, userInfo.right);
        SharedManager.getInstance().setValue(SharedManager.KEY_USER_RIGHT_MENU, userInfo.rightMenu);
        SharedManager.getInstance().setValue(SharedManager.KEY_USER_NAME, userInfo.username);
        SharedManager.getInstance().setValue(SharedManager.KEY_USER_ID, userInfo.userId);
        SharedManager.getInstance().setValue(SharedManager.KEY_USER_JTI, userInfo.jti);
    }

    /**
     * 获取验证码
     *
     * @param phoneNumber phone number
     */
    private void doGetSmsCode(String phoneNumber) {
        loginModule.getSmsCode(phoneNumber, new IContract.IModule.IModelObserver<Object, RxException>() {
            @Override
            public void onNotify(Object data) {
                postEvent(true, ACTION_GET_SMS_CODE_RESULT);
            }

            @Override
            public void onError(RxException e) {
                postEvent(false, R.string.text_toast_get_sms_error, ACTION_GET_SMS_CODE_RESULT);
            }
        });
    }

    /**
     * 验证用户登录信息
     *
     * @param auto                 "1":系统自动生成需要完善信息, "0":非系统生成已经完善信息
     * @param userEnterpriseStatus 企业用户状态（3：启用，4：禁用，5：待审核，6：审核不通过，7：移除）
     * @param userStatus           用户状态（1：激活2：未激活）
     * @param optionRight          操作权限列表
     * @param accessRight          访问权限列表
     * @return
     */
    private boolean verifyUserInfo(String auto, String userEnterpriseStatus, int userStatus, String optionRight, String accessRight) {
        if (auto.equals("0")) {
            switch (userEnterpriseStatus) {
                case "3":
                    if (userStatus == 1) {
                        if (optionRight == null && accessRight == null) {
                            postEvent(R.string.text_toast_user_info_error1, ACTION_USER_INFO_VERIFY_ERROR);
                        } else {
                            return true;
                        }
                    } else {
                        postEvent(R.string.text_toast_user_info_error2, ACTION_USER_INFO_VERIFY_ERROR);
                    }
                    break;
                case "5":
                    postEvent(R.string.text_toast_user_info_error3, ACTION_USER_INFO_VERIFY_ERROR);
                    break;
                case "6":
                    postEvent(R.string.text_toast_user_info_error4, ACTION_USER_INFO_VERIFY_ERROR);
                    break;
                default:
                    postEvent(R.string.text_toast_user_info_error5, ACTION_USER_INFO_VERIFY_ERROR);
                    break;
            }
        } else {
            postEvent(R.string.text_toast_user_info_error6, ACTION_USER_INFO_VERIFY_ERROR);
        }
        return false;
    }

    @Override
    public void doInitProcess() {

    }
}
